<?php
    namespace lactone\Core\data;

    class SocketData{

        protected $array;

        protected $string;

        public function __construct($data = false){
            if($data) $this->parse($data);
        }

        /**
         * 解析传递过来的数据
         * @param $data
         * @return bool
         */
        public function parse($data){
            if(is_array($data)){
                $this->array = $data;
                $this->string = json_encode($data);
                return true;
            }

            if(is_string($data) && ($json = @json_decode($data,true))){
                $this->string = $data;
                $this->array = $json;
                return true;
            }

            return false;
        }

        /**
         * 创建一个data
         * @param $data
         * @param string $type
         * @return bool
         */
        public function create($data,$type='data'){
            $this->parse(['type'=>$type,'data'=>$data]);
            return true;
        }

        public function __get($key){
            if(!$this->array) return false;
            if(isset($this->array[$key]))
                return $this->array[$key];
        }

        public function __toString(){
            return $this->string;
        }

        public function __toArray(){
            return $this->array;
        }
    }